package com.shujia.jdbc;

import org.junit.Test;

import java.sql.*;

public class JdbcCrud2 {

    @Test
    public void update() {
        int id = 3;
        String pwd = "111111";
        String address = "上海";
        String sql = "update t_user set password = md5(?), address = ? where id = ?";

        int i = updateRecord(sql, pwd, address, id);
        System.out.println(i);
    }


    //实现注册功能
    @Test
    public void registerTest() throws SQLException {

//        String sql = "insert into t_user(user_name, `password`, birth, address) " +
//                "values('王五', md5('123456') , '2012-09-20 15:16:19', '广东')";
        String sql = "insert into t_user(user_name, `password`, birth, address) " +
                "values(?, md5(?) , '2012-09-20 15:16:19', ?)";

        updateRecord(sql, "小明", "111111", "北京");


    }

    /*
    封装的增删改通用方法
     */
    public int updateRecord(String sql, Object... args) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = JdbcUtil.getConnection();

            // 关闭自动提交
            connection.setAutoCommit(false);

            ps = connection.prepareStatement(sql);

            for (int i = 0; i < args.length; i++) {
                // 把数组里面的元素填充到 PreparedStatement 对象里
                ps.setObject(i + 1, args[i]);
            }
            int i = ps.executeUpdate();


            // 提交事务
            connection.commit();
            return i;
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚操作
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
//            关闭资源
            JdbcUtil.close(connection, ps);
        }
        return 0;
    }




}
